package com.skillworld.webapp.web.pages.rest.user;

import java.util.Locale;
import java.util.Set;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.department.Department;
import com.skillworld.webapp.model.team.Team;
import com.skillworld.webapp.model.user.User;
import com.skillworld.webapp.model.userservice.UserService;
import com.skillworld.webapp.web.services.I18n;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class ViewTeam {

    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;

    @Property
    private Team team;
    
    @SuppressWarnings("unused")
    @Property
    private Locale locale;
    
    @SuppressWarnings("unused")
    @Property
    private User member;
    
    @SuppressWarnings("unused")
    @Property
    private Department dept; // loop iterator
    
    @InjectService("I18n")
    private I18n i18n;
    
    @SuppressWarnings("unused")
    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
    
    @Inject
    private UserService userService;

    @Inject
    private Request request;
 

    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if(!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String teamParam = request.getParameter("team");
        String langParam = request.getParameter("lang");

        if (teamParam == null)
        { 
            this.errorMessage = ErrorMessages.INVALID_ARGUMENTS; 
            return;
        }
            
        try 
        { 
            locale = i18n.selectLocale(langParam);
            long teamId = Long.parseLong(teamParam);
            team = this.userService.findTeam(teamId);
        }
        catch (NumberFormatException e)
        { this.errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InstanceNotFoundException e)
        { this.errorMessage = ErrorMessages.TEAM_NOT_FOUND; } 
    }  
}
